<?php
/* 
 * $Id: select.php 11 2010-11-24 22:10:53Z LEON $
 * $Author: LEON $
 * $LastChangedDate: 2010-11-24 22:10:53 +0000 (Wed, 24 Nov 2010) $
 * $Revision: 11 $
 */
namespace cmFly\db\sql_constructors\mysql;
use cmFly\db\sql_constructors;
class select extends sql_constructors\select {
    public function create_query() {
	$joins='';
	$quote_style=$this->get_column_quote_style();
	if(count($this->joins)) {
	    foreach($this->joins as $arr) {
		$v=$arr['join'];
		switch($arr['type']) {
		    default:
			$join_type='LEFT';
			break;
		}
		$joins.=$join_type.' JOIN '.
		    $quote_style.$v->from.$quote_style.' AS '.$quote_style.$v->pseudo_name.$quote_style.
			' ON '.$v->build_where()."\n\t";
	    }
	}
	$fields='';
	$fields_arr=$this->fields;
	if(count($fields_arr)) {
	    $last_all=false;
	    foreach($fields_arr as $k=>$v) {
		if(!\count($v)) {
		    $fields.=(!$last_all?$quote_style:'').', '.$quote_style.$k.$quote_style.'.*';
		    $last_all=true;
		    continue;
		}
		$fields.=(!$last_all?$quote_style:'').', '.$quote_style.$k.
		    $quote_style.'.'.$quote_style.implode($quote_style.', '.
		    $quote_style.$k.$quote_style.'.'.$quote_style,\array_keys($v['fields']));
		$last_all=false;
	    }
	    $fields=substr($fields,3).(!$last_all?$quote_style:'');
	}
	else {
	    $fields=$quote_style.$this->pseudo_name.$quote_style.'.*';
	}
	/**
	 * @todo Реализовать добавление ORDER BY и GROUP BY
	 */
	$sql='SELECT '.$fields."\n\t".
		    'FROM '.$quote_style.$this->from.$quote_style.' AS '.
		    $quote_style.$this->pseudo_name.$quote_style."\n\t"
		    .($joins!=''?$joins."\t":'').
		    ($this->where['logic']!=NULL?'WHERE '.$this->build_where()."\n\t":'').
		    ($this->order_by?'ORDER BY '.$this->order_by."\n\t":'').
		    ($this->group_by?'GROUP BY'.$this->group_by."\n\t":'');
	return $sql;
    }
    public function get_column_quote_style() {
	return '`';
    }
}